package com.j.lemon.learn.thread.ThreadControl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author lijunjun
 * @Date 2019-01-29 10:32
 * @Description
 */
public class ListAddRemove {
    public static final Object object = new Object();
    public static List<Integer> list = new ArrayList<>();


    public static void main(String[] args) {
        AddThread addThread = new AddThread();
        RemoveThread removeThread = new RemoveThread();
        Thread t1 = new Thread(addThread);
        Thread t2 = new Thread(removeThread);
        Thread t3 = new Thread(removeThread);

        t2.start();
        t1.start();
        t3.start();
    }
}

class RemoveThread implements Runnable {

    private final Object object = ListAddRemove.object;

    @Override
    public void run() {
        synchronized (object) {
            System.out.println(Thread.currentThread().getName() + "删除线程开始执行");
            while (ListAddRemove.list.size() == 0) {
                try {
                    System.out.println(Thread.currentThread().getName() + "删除线程发现lit为空，调用wait（）方法");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            ListAddRemove.list.remove(0);
            System.out.println(Thread.currentThread().getName()+"删除完成");
        }
    }
}

class AddThread implements Runnable {
    private final Object object = ListAddRemove.object;

    @Override
    public void run() {
        synchronized (object) {
            System.out.println("add线程执行");
            ListAddRemove.list.add(new Random().nextInt());
            System.out.println("add线程数据添加完成,调用notifyAll（）");
            object.notifyAll();
            System.out.println("add线程调用notifyAll（）后");
        }
    }
}
